package com.itdct.onflow.system.generator.core

import com.itdct.onflow.com.itdct.onflow.system.generator.config.SysGeneratorConfig
import com.itdct.onflow.com.itdct.onflow.system.generator.context.SysGeneratorContext
import com.itdct.onflow.com.itdct.onflow.system.generator.util.JdbcHelper
import com.itdct.onflow.generator.model.ClassModel
import com.itdct.onflow.system.component.entity.SysComponentEntity
import com.itdct.onflow.system.menu.entity.SysMenuEntity
import java.sql.Connection

/**
 * @author Zhouwx
 * @date 2025/9/16 11:36:56
 * @version 1.0
 * @description
 */
class SyncComponentCore {
    /**
     * 同步按钮组件
     */
    fun syncComponent(context: SysGeneratorContext, generatorConfig: SysGeneratorConfig) {
        val connection = context.connection!!
        val sysComponentClassModel = context.sysComponentClassModel
        val sysMenuClassModel = context.sysMenuClassModel
        val className = context.classModel.className
        val pageSysMenuEntity = JdbcHelper.selectOne(connection, sysMenuClassModel, Pair(SysMenuEntity::name, className + "Page"))

        var pageMenuId = 0L
        if (pageSysMenuEntity != null) {
            pageMenuId = pageSysMenuEntity.id!!
        }

        val editSysMenuEntity = JdbcHelper.selectOne(connection, sysMenuClassModel, Pair(SysMenuEntity::name, className + "Edit"))
        var editMenuId = 0L
        if (editSysMenuEntity != null) {
            editMenuId = editSysMenuEntity.id!!
        }

        val componentEntities = ArrayList<SysComponentEntity>()

        checkAndAdd(connection, sysComponentClassModel, pageMenuId, componentEntities, "add", "新增")

        checkAndAdd(connection, sysComponentClassModel, pageMenuId, componentEntities, "edit", "编辑")

        checkAndAdd(connection, sysComponentClassModel, pageMenuId, componentEntities, "delete", "删除")

        checkAndAdd(connection, sysComponentClassModel, editMenuId, componentEntities, "save", "保存")

        JdbcHelper.insertBatch(connection, sysComponentClassModel, componentEntities)
    }

    private fun checkAndAdd(
        connection: Connection,
        sysComponentClassModel: ClassModel,
        pageMenuId: Long,
        componentEntities: ArrayList<SysComponentEntity>,
        code: String,
        title: String
    ) {
        val addButton = JdbcHelper.selectOne(
            connection,
            sysComponentClassModel,
            Pair(SysComponentEntity::menuId, pageMenuId),
            Pair(SysComponentEntity::code, code)
        )

        if (addButton == null) {
            val buttonEntity = SysComponentEntity()
            buttonEntity.menuId = pageMenuId
            buttonEntity.type = "按钮"
            buttonEntity.title = title
            buttonEntity.code = code
            componentEntities.add(buttonEntity)
        }
    }
}